package cn.felord.websocket.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * webSocket 拦截器  处理握手前  握手后的逻辑
 *
 * @author Dax
 * @since 11:45  2018/7/6
 */
public class DefaultWebSocketInterceptor implements HandshakeInterceptor {
    private static final Logger log = LoggerFactory.getLogger(DefaultWebSocketInterceptor.class);

    /**
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param map                webSocket  session 参数 处理后会被带到  {@link WebSocketSession} 中去
     * @return 返回是否继续握手
     * @throws Exception
     */
    @Override
    public boolean beforeHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Map<String, Object> map) throws Exception {
        log.info("握手前……");
        ServletServerHttpRequest servletServerHttpRequest= (ServletServerHttpRequest) serverHttpRequest;
       HttpHeaders httpHeaders= servletServerHttpRequest.getHeaders();
            System.out.println(httpHeaders.entrySet());
      String path=  getSockJsPath(servletServerHttpRequest.getServletRequest());
        System.out.println(path);
      // 前置处理是否同意继续握手
        return true;
    }

    /**
     * 在握手后执行 无论 握手是否成功都会执行    可以捕获异常  没有异常为null
     *
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @param webSocketHandler
     * @param e
     */
    @Override
    public void afterHandshake(ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse, WebSocketHandler webSocketHandler, Exception e) {
      //  并不代表握手成功
    }

    private String getSockJsPath(HttpServletRequest servletRequest) {

        String attribute = HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE;
        String path = (String) servletRequest.getAttribute(attribute);
        return (path.length() > 0 && path.charAt(0) != '/' ? "/" + path : path);
    }
}
